package com.ymxx.jweb.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import com.ymxx.jweb.exception.YmxxException;

/**
 * @author Administrator
 * 
 */
public class Encryption {

	/**
	 *  
	 */
	private Encryption() {}

	/**
	 * 获取字符串的MD5值
	 * @param str
	 * @return
	 */
	public static String getMD5(String str) {

		if (null == str) {
			throw new YmxxException("for input illegal parameter,null");
		}
		return getMD5(str.getBytes());
	}

	/**
	 * 将字节数组转换成MD5
	 * @param source
	 * @return
	 */
	public static String getMD5(byte[] source) {
		
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(source);
			byte tmp[] = md.digest();
			
			return byteArrayToHex(tmp);

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			throw new YmxxException(e.getMessage());
		}
	}

	/**
	 * 计算文件的MD5值
	 * @param f
	 * @return
	 * @throws IOException
	 */
	public static String getMD5(File f) throws IOException {
		int bufferSize = 256 * 1024;
		FileInputStream fileInputStream = null;
		DigestInputStream digestInputStream = null;
		try {
			MessageDigest messageDigest = MessageDigest.getInstance("MD5");
			fileInputStream = new FileInputStream(f);
			digestInputStream = new DigestInputStream(fileInputStream,messageDigest);
			byte[] buffer = new byte[bufferSize];
			while (digestInputStream.read(buffer) > 0);
			messageDigest = digestInputStream.getMessageDigest();
			byte[] resultByteArray = messageDigest.digest();
			return byteArrayToHex(resultByteArray);

		} catch (NoSuchAlgorithmException e) {
			return null;
		} finally {
			try {
				digestInputStream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			try{
				fileInputStream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	}

	/**
	 * 转换16进制
	 * @param byteArray
	 * @return
	 */
	private static String byteArrayToHex(byte[] byteArray) {
		char[] hexDigits = { 
					'0', '1','2','3', 
					'4', '5','6','7', 
					'8', '9','A','B', 
					'C', 'D','E','F'
				};
		char[] resultCharArray = new char[byteArray.length * 2];
		int index = 0;
		for (byte b : byteArray) {
			resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
			resultCharArray[index++] = hexDigits[b & 0xf];
		}
		return new String(resultCharArray); 
	}
}
